#!/usr/bin/env python
# coding=utf-8

import os
import time
import urllib
import wsgiref.handlers
import hashlib

from google.appengine.api.labs import taskqueue
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import urlfetch
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.api import users

from auth import SECRET,ROOTSITE
from suki.cloud import Datum,Admin
from suki.cloud.purview import CheckAuth, DoAuth, CheckAuthSilence, DoAuthSilence

from suki.cloud.bot.sessions import Session
from suki.cloud.bot.cookies import Cookies


class CcdjhMarxHandler(webapp.RequestHandler):
	def lockKey(self,webAddress = '/lock'):
		nowAddress = webAddress
		if (ROOTSITE == 'google'):
			if not users.is_current_user_admin():
				self.redirect(users.create_login_url(self.request.uri))
		elif (ROOTSITE == 'silence'):
			self.session = Session()
			if CheckAuthSilence(self) is False:
				return DoAuthSilence(self, nowAddress)
		else:
			self.session = Session()
			if CheckAuth(self) is False:
				return DoAuth(self, nowAddress)
#lock login  bashboard
	def lockmessage(self,message):
		if (message == 'password-wrong'):
			return "welcome to cccccc"
		elif (message == 'author-name-wrong'):
			pass
		elif (message == 'message=no-author'):
			pass
		elif (message == 'have-admin1'):
			pass
		elif (message == 'two-wrong'):
			pass
		elif (message == 'have-admin2'):
			pass
		elif (message == 'creatd-admin'):
			pass
		elif (message == 'creatd-article'):
			return "The now Article"
		elif (message == 'edit-article'):
			pass
		elif (message == 'delete-article'):
			pass
		elif (message == 'add-category'):
			pass
		elif (message == 'delete-category'):
			pass
		else:
			pass


class LockLoginHandler(webapp.RequestHandler):
	def get(self):
		if (ROOTSITE == 'google'):
			pass#google
		elif (ROOTSITE == 'silence'):
			template_values = {}
			template_values['category'] = "category"
			path = os.path.join(os.path.dirname(__file__), 'tpl', 'lock', 'default', 'login-silence.html')
			self.response.out.write(template.render(path, template_values))
		else:
			self.session = Session()
			template_values = {}
			if 'message' in self.session:
				message = self.session['message']
				del self.session['message']
			else:
				message = None
			template_values['message'] = message
			destination = None
			destination = self.request.get('destination')
			template_values['destination'] = destination
			path = os.path.join(os.path.dirname(__file__), 'tpl','lock','default', 'login.html')
			output = template.render(path, template_values)
			self.response.out.write(output)

	def post(self):
		if (ROOTSITE == 'google'):
			pass#google
		elif (ROOTSITE == 'silence'):
			a = db.GqlQuery("SELECT * FROM Admin")
			if a.count() == 1:
				if a[0].author_name == self.request.get('author_name'):
					#p = self.request.get('author_password')
					#pp = hashlib.sha1(self.request.get('author_password')).hexdigest()
					if a[0].author_password == hashlib.sha1(self.request.get('author_password')).hexdigest():
						cookies = Cookies(self, max_age = 86400, path = '/')
						cookies['auth'] = hashlib.sha1(a[0].author_password + ':' + a[0].author_name).hexdigest()
						self.redirect('/indoor?message=you-are-login')
					else:
						self.redirect('/lock?message=password-wrong')
				else:
					self.redirect('/lock?message=author-name-wrong')
			else:
				self.redirect('/lock?message=no-author')
		else:
			self.session = Session()
			destination = self.request.get('destination')
			if (str(destination) == ''):
				destination = None
			cookies = Cookies(self, max_age = 86400, path = '/')
			s = self.request.get('secret')
			site_domain = "ccdjh"
			sha1 = hashlib.sha1(s).hexdigest()
			if (sha1 == SECRET):
				cookies['auth'] = hashlib.sha1(SECRET + ':' + site_domain).hexdigest()
				if destination is None:
					self.redirect('/indoor')
				else:
					self.redirect(str(destination))
			else:
				self.session['message'] = "Your entered secret passphrase isn't correct"
				if destination is None:
					self.redirect('/lock')
				else:
					self.redirect('/lock?destination=' + str(destination))


class LockSignoutHandler(webapp.RequestHandler):
	def get(self):
		w = 'google'
		if (ROOTSITE == 'google'):
			self.redirect(users.create_logout_url('/'))
		elif (ROOTSITE == 'silence'):
			cookies = Cookies(self, max_age = 86400, path = '/')
			if 'auth' in cookies:
				del cookies['auth']
			template_values = {}
			path = os.path.join(os.path.dirname(__file__), 'tpl', 'lock', 'default', 'logout.html')
			output =template.render(path,template_values)
			self.response.out.write(output)
		else:
			self.session = Session()
			cookies = Cookies(self, max_age = 86400, path = '/')
			if 'auth' in cookies:
				del cookies['auth']
			template_values = {}
			path = os.path.join(os.path.dirname(__file__), 'tpl', 'lock', 'default', 'logout.html')
			output =template.render(path,template_values)
			self.response.out.write(output)

class LockRegisterHandler(webapp.RequestHandler):
	def get(self):
		a = db.GqlQuery("SELECT * FROM Admin")
		if a.count() >= 1:
			self.redirect('/lock/login?pass=have-admin1')
		template_values = {}
		template_values['category'] = "category"
		path = os.path.join(os.path.dirname(__file__), 'tpl', 'lock', 'default', 'register.html')
		self.response.out.write(template.render(path, template_values))

	def post(self):
		#q = db.GqlQuery("SELECT * FROM Admin")
		author_name = self.request.get('author_name')
		author_password = self.request.get('author_password')
		author_password_confirm = self.request.get('author_password_confirm')
		if author_password != author_password_confirm:
			self.redirect('/lock/register?pass=two-wrong')
		a = db.GqlQuery("SELECT * FROM Admin")
		if a.count() >= 1:
			self.redirect('/lock/login?message=have-admin2')
		else:
			b = Admin()
			b.author_name = author_name
			b.author_password = hashlib.sha1(author_password).hexdigest()
			b.put()
			self.redirect('/lock/login?message=creatd-admin')


def main():
    application = webapp.WSGIApplication([
    ('/lock', LockLoginHandler),
    ('/lock/login', LockLoginHandler),
    ('/lock/logout', LockSignoutHandler),
    ('/lock/register', LockRegisterHandler)
    ],
                                       debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
		
		
